package com.blue.wechat.invoke.spi.media;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.core.dict.HttpMethod;
import com.blue.core.util.UUID;
import com.blue.core.util.UrlUtil;
import com.blue.http.client.DownloadResult;
import com.blue.http.util.HttpException;
import com.blue.wechat.cache.Wechat;
import com.blue.wechat.invoke.BaseInvoker;
import com.blue.wechat.invoke.WechatInvoker;
import com.blue.wechat.invoke.annotation.WechatUrl;
import com.blue.wechat.invoke.model.media.DownloadMedia;

/**
 * 下载临时素材
 * 
 * @author zhengj
 * @since 1.0 2017年1月26日
 */
@WechatUrl(WechatInvoker.GET_MEDIA)
public class DownloadMediaInvoker extends BaseInvoker<DownloadMedia>
{
	private static Logger logger = LoggerFactory.getLogger(DownloadMediaInvoker.class);
	
	public DownloadMediaInvoker()
	{
	}

	@Override
	protected WechatInvoker getInvoker()
	{
		return WechatInvoker.GET_MEDIA;
	}

	@Override
	protected String invoke(String url, HttpMethod method, Object post) throws Exception
	{
		CloseableHttpClient httpClient = httpInvoker.getHttpClient();
		HttpGet request = new HttpGet(url);
		DownloadMedia media = new DownloadMedia();
		boolean other = false;
		String json = null;
		String path = UrlUtil.getTempDir() + UUID.generator();
		try (CloseableHttpResponse response = httpClient.execute(request);)
		{
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() != HttpStatus.SC_OK) // http调用失败
				throw new HttpException(statusLine.getStatusCode(), "下载失败：" + statusLine.getReasonPhrase());
			
			HttpEntity entity = response.getEntity();
			if (!entity.isStreaming())
				throw new HttpException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "下载失败：" + EntityUtils.toString(entity, Consts.UTF_8));
				
			media.setSize((int)entity.getContentLength());
			Header type = entity.getContentType();
			logger.info(type.toString());
			if (type != null)
			{
				int pos = type.getValue().indexOf(';');
				if (pos == -1)
					media.setMimeType(type.getValue());
				else
					media.setMimeType(type.getValue().substring(0, pos));
				
				if (media.getMimeType().startsWith("image"))
					path += ".jpg";
				else if (media.getMimeType().startsWith("audio"))
					path += ".amr";
				else
					other = true;
			}
			media.setPath(path);
			if (!other)
			{
				File file = new File(path);
				try (FileOutputStream fos = new FileOutputStream(file);)
				{
					entity.writeTo(fos);
				}
				return JSON.toJSONString(media);
			}
			else
			{
				json = IOUtils.toString(entity.getContent(), "UTF-8");
				logger.info("下载为 json 数据：{}", json);
			}
		}
		
		if (json.contains("\"errcode\":"))
			return json;
		
		JSONObject object = JSON.parseObject(json);
		String video = object.getString("video_url");
		logger.info("视频地址：{}", video);
		path = UrlUtil.getTempDir() + UUID.generator() + ".mp4";
		File file = new File(path);
		DownloadResult result = httpInvoker.download(video, file);
		DownloadMedia message = new DownloadMedia();
		message.setMimeType(result.getMimeType());
		message.setSize(result.getSize());
		message.setPath(path);
		return JSON.toJSONString(message);
		
	}

	@Override
	protected DownloadMedia handleSuccess(String resp, Wechat wechat)
	{
		DownloadMedia message = JSON.parseObject(resp, DownloadMedia.class);
		return message;
	}
	
}
